/**
 * 通用js方法封装处理
 */
import { ElMessageBox } from 'element-plus'

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time
        .replace(new RegExp(/-/gm), '/')
        .replace('T', ' ')
        .replace(new RegExp(/\.[\d]{3}/gm), '')
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields()
  }
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
  let search = params
  search.params =
    typeof search.params === 'object' && search.params !== null && !Array.isArray(search.params)
      ? search.params
      : {}
  dateRange = Array.isArray(dateRange) ? dateRange : []
  if (typeof propName === 'undefined') {
    search.params['beginTime'] = dateRange[0]
    search.params['endTime'] = dateRange[1]
  } else {
    search.params['begin' + propName] = dateRange[0]
    search.params['end' + propName] = dateRange[1]
  }
  return search
}

// 回显数据字典
export function selectDictLabel(datas, value) {
  if (value === undefined) {
    return ''
  }
  var actions = []
  Object.keys(datas).some((key) => {
    if (datas[key].value == '' + value) {
      actions.push(datas[key].label)
      return true
    }
  })
  if (actions.length === 0) {
    actions.push(value)
  }
  return actions.join('')
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
  if (value === undefined || value.length === 0) {
    return ''
  }
  if (Array.isArray(value)) {
    value = value.join(',')
  }
  var actions = []
  var currentSeparator = undefined === separator ? ',' : separator
  var temp = value.split(currentSeparator)
  Object.keys(value.split(currentSeparator)).some((val) => {
    var match = false
    Object.keys(datas).some((key) => {
      if (datas[key].value == '' + temp[val]) {
        actions.push(datas[key].label + currentSeparator)
        match = true
      }
    })
    if (!match) {
      actions.push(temp[val] + currentSeparator)
    }
  })
  return actions.join('').substring(0, actions.join('').length - 1)
}

// 字符串格式化(%s )
export function sprintf(str) {
  var args = arguments,
    flag = true,
    i = 1
  str = str.replace(/%s/g, function () {
    var arg = args[i++]
    if (typeof arg === 'undefined') {
      flag = false
      return ''
    }
    return arg
  })
  return flag ? str : ''
}

// 转换字符串，undefined,null等转化为""
export function parseStrEmpty(str) {
  if (!str || str == 'undefined' || str == 'null') {
    return ''
  }
  return str
}

// 数据合并
export function mergeRecursive(source, target) {
  for (var p in target) {
    try {
      if (target[p].constructor == Object) {
        source[p] = mergeRecursive(source[p], target[p])
      } else {
        source[p] = target[p]
      }
    } catch (e) {
      source[p] = target[p]
    }
  }
  return source
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  }

  var childrenListMap = {}
  var nodeIds = {}
  var tree = []

  for (let d of data) {
    let parentId = d[config.parentId]
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = []
    }
    nodeIds[d[config.id]] = d
    childrenListMap[parentId].push(d)
  }

  for (let d of data) {
    let parentId = d[config.parentId]
    if (nodeIds[parentId] == null) {
      tree.push(d)
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t)
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]]
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c)
      }
    }
  }
  return tree
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    var part = encodeURIComponent(propName) + '='
    if (value !== null && value !== '' && typeof value !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== '' && typeof value[key] !== 'undefined') {
            let params = propName + '[' + key + ']'
            var subPart = encodeURIComponent(params) + '='
            result += subPart + encodeURIComponent(value[key]) + '&'
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&'
      }
    }
  }
  return result
}

// 返回项目路径
export function getNormalPath(p) {
  if (p.length === 0 || !p || p == 'undefined') {
    return p
  }
  let res = p.replace('//', '/')
  if (res[res.length - 1] === '/') {
    return res.slice(0, res.length - 1)
  }
  return res
}

// 验证是否为blob格式
export function blobValidate(data) {
  return data.type !== 'application/json'
}

const getType = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLocaleLowerCase()

export const isObject = (obj) => getType(obj) === 'object'

/**
 * 通用修改前二次确认弹窗
 * @param {boolean} hide
 * @param {string} text
 * @returns Promise
 */
export function handleUpdConfirm(hide = false, text = '') {
  if (hide) {
    return Promise.resolve()
  } else {
    return ElMessageBox.confirm(text, '系统提示', { type: 'warning' })
  }
}

/**文本域内容添加p标签 */
export function formatTexarea(text, type) {
  if (!text) return ''
  if (type) {
    return text.replace('<p>', '').replace('</p>', '').split('<br/>').join('\n')
  }
  const str = text?.includes('\n') ? text?.split('\n').join('<br/>') : text
  return `<p>${str}</p>`
}

/**
 ** 减法函数，用来得到精确的减法结果
 ** 说明：javascript的减法结果会有误差，在两个浮点数相减的时候会比较明显。这个函数返回较为精确的减法结果。
 ** 调用：accSub(arg1,arg2)
 ** 返回值：arg1加上arg2的精确结果
 **/
export function accSub(arg1, arg2) {
  let r1
  let r2
  let m
  let n
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2)) // last modify by deeka //动态控制精度长度
  n = r1 >= r2 ? r1 : r2
  return Number(((arg1 * m - arg2 * m) / m).toFixed(n))
}

// 千分位
export function rbstateFormat(value) {
  if (!value) return '0'

  // 将值转换为字符串
  value = value.toString()

  // 将值分割成两部分：整数和小数
  var parts = value.split('.')
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  return parts.join('.')
}

//除法函数，用来得到精确的除法结果
//说明：javascript的除法结果会有误差，在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
//调用：divide(arg1,arg2)
//返回值：arg1除以arg2的精确结果
export function divide(arg1, arg2) {
  var t1 = 0,
    t2 = 0,
    r1,
    r2
  try {
    t1 = arg1.toString().split('.')[1].length
  } catch (e) {
    t1 = 0
  }
  try {
    t2 = arg2.toString().split('.')[1].length
  } catch (e) {
    t2 = 0
  }
  r1 = Number(arg1.toString().replace('.', ''))
  r2 = Number(arg2.toString().replace('.', ''))
  return mul(r1 / r2, Math.pow(10, t2 - t1))
}

//乘法函数，用来得到精确的乘法结果
//说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
//调用：mul(arg1,arg2)
//返回值：arg1乘以arg2的精确结果
export function mul(arg1, arg2) {
  var m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString()
  try {
    m += s1.split('.')[1].length
  } catch (e) {
    m = 0
  }
  try {
    m += s2.split('.')[1].length
  } catch (e) {
    m = m || 0
  }
  return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m)
}
/**加法运算，避免数据相加小数点后产生多位数和计算精度损失。
 */
export function additionOperation(num1, num2) {
  if (typeof num1 !== 'number' || isNaN(num1)) {
    num1 = 0
  }
  if (typeof num2 !== 'number' || isNaN(num2)) {
    num2 = 0
  }
  return (Math.round((num1 + num2) * 100) / 100).toFixed(2)
}
/**
 * 设备投放列表排列格式，传入排入的设备类型，返回相应的排列格式
 * @param {Number} machineType 设备类型
 * */
export function handProjectList(machineType) {
  const newGroupRoadNumbers = {
    2: [
      '11',
      '12',
      '13',
      '14',

      '21',
      '22',
      '23',
      '24',

      '31',
      '32',
      '33',
      '34',

      '41',
      '42',
      '43',
      '44',

      '51',
      '52',
      '53',
      '54',

      '61',
      '62',
      '63',
      '64',

      '71',
      '72',
      '73',
      '74',

      '81',
      '82',
      '83',
      '84',

      '91',
      '92',
      '93',
      '94',

      '101',
      '102',
      '103',
      '104',

      '111',
      '112',
      '113',
      '114',

      '121',
      '122',
      '123',
      '124',

      '131',
      '132',
      '133',
      '134',

      '141',
      '142',
      '143',
      '144',

      '151',
      '152',
      '153',
      '154'
    ],
    3: [
      '11',
      '12',
      '13',

      '21',
      '22',
      '23',

      '31',
      '32',
      '33',

      '41',
      '42',
      '43',

      '51',
      '52',
      '53',

      '61',
      '62',
      '63',

      '71',
      '72',
      '73',

      '81',
      '82',
      '83'
    ],
    4: [
      '11',
      '12',
      '13',
      '14',

      '21',
      '22',
      '23',
      '24',

      '31',
      '32',
      '33',
      '34',

      '41',
      '42',
      '43',
      '44',

      '51',
      '52',
      '53',
      '54',

      '61',
      '62',
      '63',
      '64',

      '71',
      '72',
      '73',
      '74',

      '81',
      '82',
      '83',
      '84',

      '91',
      '92',
      '93',
      '94'
    ],
    5: [
      '11',
      '12',
      '13',

      '21',
      '22',
      '23',

      '31',
      '32',
      '33',

      '41',
      '42',
      '43',

      '51',
      '52',
      '53',

      '61',
      '62',
      '63',

      '71',
      '72',
      '73',

      '81',
      '82',
      '83',

      '91',
      '92',
      '93',

      '101',
      '102',
      '103',

      '111',
      '112',
      '113',

      '121',
      '122',
      '123'
    ]
  }
  let groupedData = []
  if (machineType === 3 || machineType === 5) {
    groupedData = newGroupRoadNumbers[machineType].reduce((acc, item, index) => {
      if (index % 3 === 0) {
        acc.push([item])
      } else {
        acc[acc.length - 1].push(item)
      }
      return acc
    }, [])
  } else {
    groupedData = newGroupRoadNumbers[machineType].reduce((acc, item, index) => {
      if (index % 4 === 0) {
        acc.push([item])
      } else {
        acc[acc.length - 1].push(item)
      }
      return acc
    }, [])
  }

  return groupedData
}

/** 过滤出所有城市的附属区域 */
export function filterAllCitiesAreas(arr, param = '0000') {
  if (!arr?.length) return null
  return arr.flatMap((item) => {
    if (
      Array.isArray(item.children) &&
      item.value.includes(param) &&
      !item.label.includes('特别行政区') &&
      !item.label.includes('台湾省')
    ) {
      return filterAllCitiesAreas(item.children)
    } else {
      return item
    }
  })
}
/** 过滤出所有城市 */
export function filterCities() {
  const globalStore = useGlobalStore()
  return globalStore.district.map((item) => ({
    ...item,
    children: item.children.map((i) => ({ ...i, children: null }))
  }))
}

import useGlobalStore from '@/store/modules/global'
import useUserStore from '@/store/modules/user'
/**匹配账号下的城市 */
export function matchCities() {
  const globalStore = useGlobalStore()
  const list = []
  const options = filterAllCitiesAreas(globalStore.district)
  globalStore.myCityList?.forEach((i) => {
    options?.find((e) => {
      if (i === e.label) {
        list.push(e)
      }
    })
  })
  return list
}

export function hasPermi(value) {
  const all_permission = '*:*:*'
  const permissions = useUserStore().permissions

  if (value && value instanceof Array && value.length > 0) {
    const permissionFlag = value

    const hasPermissions = permissions.some((permission) => {
      return all_permission === permission || permissionFlag.includes(permission)
    })
    if (!hasPermissions) {
      return false
    } else {
      return true
    }
  } else {
    return false
  }
}
/** 处理区域城市 */
export function handleAreaName(arr = [], type = false) {
  const district = computed(() => matchCities())

  console.log(arr)
  let name = ''
  arr.length &&
    district.value?.some(({ value, label, children }) => {
      if (value == arr[0]) {
        name += label
        children?.map(({ value, label, children }) => {
          if (value == arr[1]) {
            name += `/${label}`
            children?.map(({ value, label }) => {
              if (value == arr[2]) {
                name += `/${label}`
                return true
              }
            })
            return true
          }
        })
        return true
      }
    })
  console.log(name)
  if (type) {
    const fullName = name.split('/')
    return fullName[0]
  }
  return name
}
